package com.fwzc.giuseppe.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.fwzc.giuseppe.MyApplication;
import com.fwzc.giuseppe.R;
import com.fwzc.giuseppe.Api.Api;
import com.fwzc.giuseppe.adapter.BannerAdapter;
import com.fwzc.giuseppe.adapter.BannerInfo;
import com.fwzc.giuseppe.adapter.HolderAdapter;
import com.fwzc.giuseppe.adapter.HolderAdapter.ViewCreator;
import com.fwzc.giuseppe.base.BaseActivity;
import com.fwzc.giuseppe.config.Config;
import com.fwzc.giuseppe.util.PhoneHelper;
import com.fwzc.giuseppe.util.Tool;
import com.fwzc.giuseppe.view.BaseViewPager.OnPageChangeListener;
import com.fwzc.giuseppe.view.LoopPageIndicator;
import com.fwzc.giuseppe.view.LoopViewPager;
import com.fwzc.giuseppe.view.LoopViewPagerAdapter;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;

public class ShoppingActivity extends BaseActivity implements OnClickListener {
	private Context context = ShoppingActivity.this;
	private ImageView Left, Right;
	private LoopViewPager mViewPager;
	private LoopViewPagerAdapter mPagerAdapter;
	private LoopPageIndicator mPagerIndicator;
	private GridView gv;
	HolderAdapter<HashMap<String, String>> mAdapter_grid;
	private List<HashMap<String, String>> data_grid = new ArrayList<HashMap<String, String>>();
	MyApplication myApp;
	int width;
	private ProgressDialog load;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shopping);

		initView();
	}

	private void initView() {
		load = new ProgressDialog(this);
		load.setMessage(getResources().getString(R.string.deal));
		load.setCancelable(false);
		
		myApp = (MyApplication) context.getApplicationContext();
		mPagerIndicator = (LoopPageIndicator) findViewById(R.id.task_list_id_indicator);
		mViewPager = (LoopViewPager) findViewById(R.id.task_list_id_banner);
		width = PhoneHelper.getScreenWidth(this);
		myApp.initImageLoader(this);

		Left = (ImageView) findViewById(R.id.back);
		Left.setOnClickListener(this);
		Right = (ImageView) findViewById(R.id.shopping);
		Right.setOnClickListener(this);

		gv = (GridView) findViewById(R.id.gridview);
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				LogUtils.d("----------------------------");
				Intent intent = new Intent(context, CommodityDetails.class);
				startActivity(intent);
			}
		});

		createAdapterGrid();
		if (Api.false_data) {
			setFalseData();
			setFalseDataGrad();
		} else {

			loadingHomePage();

		}

	}

	private void createAdapterGrid() {
		ViewCreator<HashMap<String, String>> creator = new ViewCreator<HashMap<String, String>>() {
			@SuppressLint("InflateParams")
			@Override
			public View createView(LayoutInflater inflater, int position,
					HashMap<String, String> map) {
				// TODO Auto-generated method stub

				return LayoutInflater.from(context).inflate(
						R.layout.item_grid_homepage, null);
			}

			@Override
			public void updateView(View view, int position,
					final HashMap<String, String> map) {
				// TODO Auto-generated method stub

				ImageView img_parents = (ImageView) view
						.findViewById(R.id.image);
				TextView tv_parents = (TextView) view.findViewById(R.id.name);
				TextView tv_sale = (TextView) view.findViewById(R.id.number);
				Button tv_price = (Button) view.findViewById(R.id.add_trolley);
				
				if (Api.false_data) {
					img_parents.setBackgroundResource(R.drawable.person);
				} else {
					imageLoader.displayImage(map.get("suiturl"), img_parents,Config.no_iv_option);// get图片

				}

				tv_parents.setText(map.get("brief"));// get文字
				tv_sale.setText("已卖:"+map.get("suitid"));
				tv_price.setText(map.get("amount"));
			}

		};

		mAdapter_grid = new HolderAdapter<HashMap<String, String>>(
				this.getLayoutInflater(), creator);
		gv.setAdapter(mAdapter_grid);
		mAdapter_grid.update(data_grid);

	}

	/**
	 * 伪数据
	 * */
	private void setFalseData() {
		ArrayList<BannerInfo> mInfos = new ArrayList<BannerInfo>();

		List<HashMap<String, String>> banner_list = new ArrayList<HashMap<String, String>>();

		HashMap<String, String> infomap = new HashMap<String, String>();

		// infomap.clear();
		infomap.put("mImgUrl",
				"http://pic2.ooopic.com/12/02/88/79bOOOPICd4_1024.jpg");
		banner_list.add(infomap);

		// infomap.clear();
		HashMap<String, String> infomap1 = new HashMap<String, String>();
		infomap1.put("mImgUrl",
				"http://sc.jb51.net/uploads/allimg/130403/2-1304030UH9634.jpg");
		banner_list.add(infomap1);

		// infomap.clear();
		HashMap<String, String> infomap2 = new HashMap<String, String>();
		infomap2.put("mImgUrl",
				"http://img5.imgtn.bdimg.com/it/u=966185025,3301197266&fm=21&gp=0.jpg");
		banner_list.add(infomap2);

		for (int i = 0; i < banner_list.size(); i++) {
			BannerInfo info = new BannerInfo();

			info.mImgUrl = banner_list.get(i).get("mImgUrl");
			System.out.println("--------info.mImgUrl------" + info.mImgUrl);
			mInfos.add(info);
		}

		mPagerIndicator
				.initIndicator(0, mInfos.size(),
						R.drawable.indicator_dot_normal,
						R.drawable.indicator_dot_focus);

		BannerAdapter mBannerAdapter = new BannerAdapter(ShoppingActivity.this,
				mInfos);
		mPagerAdapter = new LoopViewPagerAdapter(mBannerAdapter);
		mViewPager.setInfinateAdapter(mPagerAdapter);
		// 添加点击事件的监听

		mViewPager.setOnPageChangeListener(new BannerPageChangeListener(mInfos
				.size()));
		mViewPager.cancelScroll();
		if (mInfos.size() > 1) {
			mViewPager.startScroll();
		} else {
			mPagerIndicator.setVisibility(View.INVISIBLE);
		}

	}

	/**
	 * 伪数据
	 */
	private void setFalseDataGrad() {

		for (int i = 0; i < 7; i++) {
			HashMap<String, String> map = new HashMap<String, String>();

			map.put("name", "衣服名字");
			map.put("sale", "卖了几件");
			map.put("price", "价格");
			map.put("categoryId", (i + 1) + "");
			data_grid.add(map);
		}
		mAdapter_grid.update(data_grid);
	}

	/**
	 * api
	 * */
	private void loadingHomePage() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.addBodyParameter("userId", "1");
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.POST, Api.SHOP_HOMEPAGE, params,new RequestCallBack<String>() {
			@Override
			public void onStart() {
				load.show();
			}

			@Override
			public void onFailure(HttpException arg0, String response) {
				load.dismiss();
				showToast("加载数据失败");
			}


					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						LogUtils.d("----------购物首页---------" + responseInfo.result);
						JSONObject jsonObject = Tool.getJsonObject(responseInfo.result);

						if (Tool.getString(jsonObject, "resultCode").equals("0")) {
							ArrayList<BannerInfo> mInfos = new ArrayList<BannerInfo>();

							JSONArray jsonArray = Tool.getJsonArray(jsonObject,"adList");
							
							data_grid.addAll(Tool.getListMapByJsonArrayString(Tool.getString(jsonObject, "dataList")));
					    	mAdapter_grid.update(data_grid);	
					    	
							if (jsonArray != null && jsonArray.length() > 0) {
								for (int i = 0; i < jsonArray.length(); i++) {
									BannerInfo info = new BannerInfo();
									JSONObject obj = Tool.getJSONObjectFromArray(jsonArray,i);
									info.mImgUrl = Tool.getString(obj,"bannerimageurl");
									info.mUrl = Tool.getString(obj, "linkUrl");
									mInfos.add(info);
								}
							}

							mPagerIndicator.initIndicator(0, mInfos.size(),R.drawable.indicator_dot_normal,R.drawable.indicator_dot_focus);

							BannerAdapter mBannerAdapter = new BannerAdapter(context, mInfos);
							mPagerAdapter = new LoopViewPagerAdapter(mBannerAdapter);
							mViewPager.setInfinateAdapter(mPagerAdapter);

							mViewPager.setOnPageChangeListener(new BannerPageChangeListener(mInfos.size()));
							mViewPager.cancelScroll();
							if (mInfos.size() > 1) {
								mViewPager.startScroll();
								load.dismiss();
							} else {
								load.dismiss();
								mPagerIndicator.setVisibility(View.INVISIBLE);
							}
						} else {
							load.dismiss();
							showToast("解析出错");
						}

					}

				});
	}

	private class BannerPageChangeListener implements OnPageChangeListener {
		//
		public static final int SCROLL_STATE_IDLE = 0;
		//
		public static final int SCROLL_STATE_DRAGGING = 1;
		//
		public static final int SCROLL_STATE_SETTLING = 2;

		private int mSize;

		public BannerPageChangeListener(int size) {
			this.mSize = size;
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			switch (state) {
			case SCROLL_STATE_IDLE:
				break;

			case SCROLL_STATE_DRAGGING:
				break;

			case SCROLL_STATE_SETTLING:
				break;
			}
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageSelected(int position) {
			int index = position % mSize;
			mPagerIndicator.refreshIndicator(index);

		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.shopping:
			startActivity(new Intent(context, ShopCartActivity.class));
			break;
		default:
			break;
		}
	}
}
